package com.maychat.controller.base;

import com.maychat.config.Consts;
import com.maychat.exception.BusinessException;
import com.maychat.exception.NoAuthException;
import com.maychat.pojo.UserInfoToken;
import com.maychat.service.impl.RedisServiceImpl;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Slf4j
@Controller
public class BaseController {
    @Autowired
    protected HttpServletRequest req;

    @Autowired
    protected RedisServiceImpl redisService;

    protected UserInfoToken getTokenObjAndValidateAdmin() throws NoAuthException, BusinessException {
        UserInfoToken tokenObj = this.getTokenObj();
        if (tokenObj.isAdmin()) return tokenObj;
        throw new BusinessException("YOU ARE NOT ADMIN!你不是管理员!");
    }

    protected UserInfoToken getTokenObj() throws NoAuthException {
        String tokenStr = req.getHeader(Consts.AUTH);
        UserInfoToken tokenObj = redisService.getUserToken(tokenStr);
        if (tokenObj == null) throw new NoAuthException("登陆超时，请重新登录");
        return tokenObj;
    }
}
